package com.authority.framework.base.controller;

import com.authority.framework.base.util.FileTypeUtil;
import com.authority.framework.base.util.StringUtils;
import com.authority.framework.base.util.laydata.ResultModel;
import com.authority.framework.base.util.laydata.ResultTools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: jxkh_m
 * @description: 上传文件处理
 * @author: Mr.Yan
 * @create: 2019-01-07 13:40
 **/
@Controller
public class uploadController {

	private ResourceLoader resourceLoader;

	@Value("${file.upload.path}")
	private String uploadPath; // 上传路径

	// 分割符
	private String mark = "/";

	private String extension = ".";

	public static final String separator = File.separator;

	/**
	 * 上传文件接口
	 *
	 * @param request
	 * @param response
	 * @param file     上传文件 参数
	 */
	@ResponseBody
	@RequestMapping(value = "/upload")
	public ResultModel upload(HttpServletRequest request, HttpServletResponse response, MultipartFile file)
			throws IOException {
		// 验证上传的文件是否为空
		if (StringUtils.isNotNull(file)) {
			//uploadPath =   System.getProperty("user.dir");

			// 获取文件名
			String fileName = file.getOriginalFilename();
			// 获取文件后缀名
			String fileExtension = FileTypeUtil.getFileExtension(fileName);
			// 获取文件类型
			String fileType = FileTypeUtil.getFileType(fileExtension);
			// 创建文件 根据 uploadPath 和 文件类型 +  后缀 创建 例如 D/imageFile/png
			String finalFilePath = uploadPath + mark + fileType + mark + fileExtension;
			// 创建文件夹
			File dir = new File(finalFilePath);
			// 不存在这个文件夹创建，存在不创建
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 名字当前时间戳
			fileName = System.currentTimeMillis() + extension + fileExtension;
			// 存放最终地址
			String transToPath = finalFilePath + mark + fileName;
			// 保存到本地
			file.transferTo(new File(transToPath));
			// 返回到前台
			Map<String, Object> resultMap = new HashMap<>();
			resultMap.put("filePath", finalFilePath);
			resultMap.put("fileName", fileName);
			return ResultTools.result(0, "", resultMap);
		} else {
			return ResultTools.result(404, "上传文件为空", null);
		}
	}

	/**
	 * 显示单张图片
	 *
	 * @return
	 */
	@RequestMapping("/show")
	@ResponseBody
	public void showPhotos(
			@RequestParam(name = "filePath", required = false) String filePath,
			@RequestParam(name = "fileName", required = false) String fileName,
			HttpServletRequest request, HttpServletResponse response
	)  {
		// 由于是读取本机的文件，file是一定要加上的， path是在application配置文件中的路径
		//return ResponseEntity.ok(resourceLoader.getResource("file:///" + filePath + mark+ fileName));
		FileInputStream fis = null;
		OutputStream os = null;
		try {
			fis = new FileInputStream(filePath + mark + fileName);
			os = response.getOutputStream();
			int count = 0;
			int i = fis.available(); // 得到文件大小
			byte[] buffer = new byte[i];
			while ((count = fis.read(buffer)) != -1) {
				os.write(buffer, 0, count);
				os.flush();
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		try {
			fis.close();
			os.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

	}

}
